import {
  OnQueueActive,
  OnQueueError,
  OnQueueWaiting,
  Process,
  Processor,
} from '@nestjs/bull';
import { Job } from 'bull';
import { MailDto } from '../dto/mail.dto';
import { MailerService } from '@nestjs-modules/mailer';

@Processor('emailSending')
export class EmailProcessor {
  constructor(private readonly mailService: MailerService) {}

  @OnQueueActive()
  onActive(job: Job<MailDto>) {
    console.log(
      `Processing job ${job.id} of type ${job.name} with data ${job.data}...`,
    );
  }
  @OnQueueError()
  onError(error: Error) {
    console.log(`Processing job ${error}...`);
  }

  @OnQueueWaiting()
  onWaiting(job: Job<MailDto>) {
    console.log(
      `Processing onWaiting job ${job.id} of type ${job.name} with data ${job.data}...`,
    );
  }

  @Process('welcome')
  async sendWelcomeEmail(job: Job<MailDto>) {
    const { data } = job;
    await this.mailService.sendMail({
      ...data.data,
      subject: 'welcome',
      template: 'welcome',
      context: {
        user: data.data.user,
      },
    });
  }

  @Process('reset-password')
  async sendResetPasswordEmail(job: Job<MailDto>) {
    const { data } = job;
    await this.mailService.sendMail({
      ...data.data,
      subject: 'Reset password',
      template: 'reset-password',
      context: {
        user: data.data.user,
      },
    });
  }
}
